﻿using Kingdee.BOS.Core.Bill;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.Interaction;
using Kingdee.BOS.Core.Metadata.FormElement;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Orm;
using Kingdee.BOS.ServiceHelper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kingdee.BOS;
using Kingdee.BOS.Core;

namespace RK
{
    public static class CreateBillView
    {
        /// <summary>
        /// 模拟用户视图，创建单据
        /// </summary>
        /// <param name="dt">单据数据，DataTable类型</param>
        /// <param name="ctx">用户上下文</param>
        /// <param name="formId">单据标识</param>
        /// <param name="entityKey">单据明细体标识</param>
        public static void create(DataTable dt, Context ctx, string formId, string entityKey)
        {
            //创建视图
            IBillView billView = CreateView(ctx, formId);
            ((IBillViewService)billView).LoadData();
            DynamicFormViewPlugInProxy eventProxy = billView.GetService<DynamicFormViewPlugInProxy>();
            eventProxy.FireOnLoad();
            //填充数据
            fillData(billView, dt, entityKey);
            //操作参数 create创建
            OperateOption saveOption = OperateOption.Create();
            //保存单据
            SaveBill(billView, saveOption, ctx);
        }
        /// <summary>
        /// 初始化视图
        /// </summary>
        /// <param name="ctx">上下文</param>
        /// <param name="formId">单据标识</param>
        /// <returns></returns>
        public static IBillView CreateView(Context ctx, string formId)
        {
            FormMetadata meta = MetaDataServiceHelper.Load(ctx, formId) as FormMetadata;
            Form form = meta.BusinessInfo.GetForm();
            Type type = Type.GetType("Kingdee.BOS.Web.Import.ImportBillView,Kingdee.BOS.Web");
            var billView = (IDynamicFormViewService)Activator.CreateInstance(type);
            BillOpenParameter openParam = CreateOpenParameter(meta, ctx);
            var provider = form.GetFormServiceProvider();
            billView.Initialize(openParam, provider);
            return billView as IBillView;
        }
        /// <summary>
        /// 初始化参数
        /// </summary>
        /// <param name="meta"></param>
        /// <param name="ctx"></param>
        /// <returns></returns>
        public static BillOpenParameter CreateOpenParameter(FormMetadata meta, Context ctx)
        {
            Form form = meta.BusinessInfo.GetForm();
            BillOpenParameter openParam = new BillOpenParameter(form.Id, meta.GetLayoutInfo().Id);
            openParam.Context = ctx;
            openParam.ServiceName = form.FormServiceName;
            openParam.PageId = Guid.NewGuid().ToString();
            openParam.FormMetaData = meta;
            openParam.Status = OperationStatus.ADDNEW;
            openParam.PkValue = null;
            openParam.CreateFrom = CreateFrom.Default;
            openParam.GroupId = "";
            openParam.ParentId = 0;
            openParam.DefaultBillTypeId = "";
            openParam.DefaultBusinessFlowId = "";
            openParam.SetCustomParameter("ShowConfirmDialogWhenChangeOrg", false);
            List<AbstractDynamicFormPlugIn> plugs = form.CreateFormPlugIns();
            openParam.SetCustomParameter(FormConst.PlugIns, plugs);
            PreOpenFormEventArgs args = new PreOpenFormEventArgs(ctx, openParam);
            foreach (var plug in plugs)
            {
                plug.PreOpenForm(args);
            }
            if (args.Cancel == true)
            {
                // 不理会插件的诉求，继续....
            }
            return openParam;
        }
        /// <summary>
        /// 保存单据
        /// </summary>
        /// <param name="billView">视图</param>
        /// <param name="saveOption">保存选项</param>
        /// <param name="ctx">上下文</param>
        public static void SaveBill(IBillView billView, OperateOption saveOption, Context ctx)
        {
            // 设置FormId
            Form form = billView.BillBusinessInfo.GetForm();
            if (form.FormIdDynamicProperty != null)
            {
                form.FormIdDynamicProperty.SetValue(billView.Model.DataObject, form.Id);
            }

            // 调用保存操作
            IOperationResult saveResult = BusinessDataServiceHelper.Save(
                        ctx,
                        billView.BillBusinessInfo,
                        billView.Model.DataObject,
                        saveOption,
                        "Save");
            // 显示处理结果
            if (saveResult == null)
            {
                billView.ShowErrMessage("未知原因导致保存失败！");
                return;
            }
            else if (saveResult.IsSuccess == true)
            {// 保存成功，直接显示
             //this.View.ShowOperateResult(saveResult.OperateResult);

                object[] pkArray = (from p in saveResult.SuccessDataEnity select p[0]).ToArray();

                var submitResult = BusinessDataServiceHelper.Submit(ctx, billView.BillBusinessInfo, pkArray, "Submit", OperateOption.Create());
                if (submitResult.IsSuccess)
                {
                    var auditResult = BusinessDataServiceHelper.Audit(ctx, billView.BillBusinessInfo, pkArray, OperateOption.Create());
                    if (auditResult.IsSuccess)
                    {
                        billView.ShowOperateResult(auditResult.OperateResult);
                    }
                }
            }
            else if (saveResult.InteractionContext != null && saveResult.InteractionContext.Option.GetInteractionFlag().Count > 0)
            {
                // 保存失败，需要用户确认问题
                InteractionUtil.DoInteraction(billView, saveResult, saveOption,
                    new Action<FormResult, IInteractionResult, OperateOption>((formResult, opResult, option) =>
                    {
                        // 用户确认完毕，重新调用保存处理
                        SaveBill(billView, option, ctx);
                    }));
            }
            // 保存失败，显示错误信息
            if (saveResult.IsShowMessage)
            {
                saveResult.MergeValidateErrors();
                billView.ShowOperateResult(saveResult.OperateResult);
                return;
            }
        }
        /// <summary>
        /// 数据填充
        /// </summary>
        /// <param name="billView"></param>
        /// <param name="dt"></param>
        public static void fillData(IBillView billView, DataTable dt, string entityKey)
        {
            IDynamicFormViewService dynamicFormView = billView as IDynamicFormViewService;
            //单据头
            billView.Model.SetItemValueByNumber("FBillTypeID", "GXHB01_SYS", 0);//单据类型
            billView.Model.SetValue("FDate", dt.Rows[0]["FDate"].ToString(), 0);//日期
            billView.Model.SetItemValueByNumber("FPrdOrgId", "003", 0);//加工组织
            billView.Model.SetItemValueByNumber("FWorkShopID", "100", 0);//加工车间
            billView.Model.SetValue("FrecId", 1, 0);//思方ID

            billView.Model.ClearNoDataRow();

            Random ran = new Random();
            //写入明细表
            //billView.Model.BatchCreateNewEntryRow("FEntity", dt.Rows.Count);
            billView.Model.BatchCreateNewEntryRow(entityKey, dt.Rows.Count);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                int RandKey = ran.Next(3, 6);
                dynamicFormView.SetItemValueByNumber("FMaterialId", dt.Rows[i]["FMaterialId"].ToString(), i);
                dynamicFormView.UpdateValue("FAuxPropId", i, int.Parse(dt.Rows[i]["FAuxPropId"].ToString()));
                dynamicFormView.UpdateValue("$$FAUXPROPID__FF100001", i, dt.Rows[i]["FF100001"].ToString());//辅助属性高长
                dynamicFormView.UpdateValue("$$FAUXPROPID__FF100002", i, dt.Rows[i]["FF100002"].ToString());//辅助属性宽
                dynamicFormView.UpdateValue("$$FAUXPROPID__FF100005", i, dt.Rows[i]["FF100005"].ToString());//辅助属性长
                dynamicFormView.UpdateValue("$$FAUXPROPID__FF100022", i, dt.Rows[i]["FF100022"].ToString());//辅助属性玻类
                dynamicFormView.SetItemValueByID("FStockId", int.Parse(dt.Rows[i]["FStockId"].ToString()), i);
                dynamicFormView.UpdateValue("FExtAuxUnitQty", i, 1);//实发数量（辅单位）
                dynamicFormView.UpdateValue("FQty", i, double.Parse(dt.Rows[i]["FQty"].ToString()) * RandKey / 100);//实发数量
                dynamicFormView.SetItemValueByNumber("F_TRPU_Assistant", "007", i);
                billView.InvokeFieldUpdateService("FExtAuxUnitQty", i);
            }
            billView.Model.ClearNoDataRow();
        }
    }
}
